package com.smedi.ismedi.authoritymanagement.core.application.query.impl;

import com.smedi.ismedi.authoritymanagement.core.application.query.TermQueryService;
import com.smedi.ismedi.authoritymanagement.core.domain.repository.TermRepository;
import com.smedi.ismedi.authoritymanagement.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: xulinjun
 * @Date: 2021-9-8 17:17
 */
@Slf4j
@Service
@AllArgsConstructor
public class TermQueryServiceImpl implements TermQueryService {
    private final Map<String, TermRepository> termRepositories = new ConcurrentHashMap<>();

    @Autowired
    public void termRepositoryInterface(Map<String, TermRepository> termRepositories) {
        this.termRepositories.clear();
        termRepositories.forEach(this.termRepositories::put);
        log.info("termRepositories: {}", this.termRepositories);
    }

    @Override
    public <T> T getTermByTermId(Long termId, Class<T> tClass) {
        TermRepository termRepository = termRepositories.get(tClass.getSimpleName());

        if (termRepository == null) {
            throw LogicException.raise(CustomError.INVALID_CLASS);
        } else {
            return (T) termRepository.selectByTermId(termId);
        }
    }
}
